package com.tpc.jginterface.util;

import com.tpc.jginterface.model.KeyBean;
import com.tpc.jginterface.util.crypto.SM2Util;
import com.tpc.jginterface.util.crypto.SM4Util;
import com.tpc.jginterface.util.http.BodyType;
import com.tpc.jginterface.util.http.OkHttpClients;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class ApiRequestUtil {

    /**
     * 发送加密请求到API
     *
     * @param serviceUrl  服务路径，例如 "/api/v1/service/7001"
     * @param requestData 请求数据（JSON格式的字符串）
     * @param appendData  追加到加密数据后的字符串，可以为null
     * @return API响应结果
     * @throws DecoderException 解码异常
     * @throws IOException      IO异常
     */
    public String sendEncryptedRequest(String serviceUrl, String requestData, String appendData, KeyBean keyBean)
            throws DecoderException, IOException {
        // SM4加密
        byte[] encode = SM4Util.encode(Hex.decodeHex(keyBean.getSm4Key()),
                requestData.getBytes(StandardCharsets.UTF_8));
        String encodeHexString = Hex.encodeHexString(encode);

        // 如果有追加数据，添加到加密后的字符串
        String finalEncodeString = appendData != null ? encodeHexString + appendData : encodeHexString;

        // SM2签名
        byte[] sign = SM2Util.sign(Hex.decodeHex(keyBean.getPrivateKey()), encodeHexString);

        // 发送请求
        return OkHttpClients.builder()
                .setUri(keyBean.getBaseUrl() + serviceUrl)
                .addHeader("pharmacyUid", keyBean.getPharmacyUid())
                .addHeader("signature", Hex.encodeHexString(sign))
                .addReqData(finalEncodeString)
                .post(BodyType.STRING)
                .sync();


    }

    /**
     * 发送加密请求到API（无追加数据版本）
     *
     * @param serviceUrl  服务路径，例如 "/api/v1/service/7001"
     * @param requestData 请求数据（JSON格式的字符串）
     * @return API响应结果
     * @throws DecoderException 解码异常
     * @throws IOException      IO异常
     */
    public String sendEncryptedRequest(String serviceUrl, String requestData, KeyBean keyBean)
            throws DecoderException, IOException {
        return sendEncryptedRequest(serviceUrl, requestData, null, keyBean);
    }
}